package com.netease.xone.fragment;

import protocol.XoneService;
import protocol.meta.LoopBack;
import Utils.StackTraceUtil;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseUtils;
import android.graphics.PixelFormat;
import android.os.Bundle;
import android.os.Handler;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.CursorAdapter;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.WindowManager;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.AlphabetIndexer;
import android.widget.EditText;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;

import com.netease.log.NTLog;
import com.netease.xone.R;
import com.netease.xone.adapter.AdapterTip;
import com.netease.xone.itemview.ItemViewTipBase;
import com.netease.xone.widget.LetterIndexView;
import com.netease.xone.widget.listview.LoadingListView;
import com.netease.xone.widget.tabview.AbsTabView.OnTabSelectListener;
import com.netease.xone.widget.tabview.TabDiscussTip;

import db.XoneDBTables.DiscussTipTable;
import db.manager.ManagerDiscussTip;


public class FragmentTipBase extends FragmentBase implements OnItemClickListener,
	LoaderManager.LoaderCallbacks<Cursor>,
	LetterIndexView.OnLetterChangeListener {
    public static final String TAG = FragmentTipBase.class.getSimpleName();
    public static final String CHARACTERS = "@ABCDEFGHIJKLMNOPQRSTUVWXYZ";
    
    
    protected int mType = -1;
    protected CursorAdapter mAdapter = null;
    protected TabDiscussTip mTabDiscussTip;
    protected LoadingListView mListView = null;
    protected LetterIndexView mLetterIndexView = null;
    protected View mRootView = null;
    protected AlphabetIndexer mAlphaIndex = null;
    
    private final class CreateWindow implements Runnable {
    	@Override
        public void run() {
    		createWindow();
    	}
    }
    
    private final class RemoveWindow implements Runnable {
		 @Override
        public void run() {
			 removeWindow();
	     }
	}

    private boolean bFirst = true;
    private boolean mShowing;
    private boolean mReady;
    private int mLoadId = TAG.hashCode();
	private CreateWindow mCreateWindow = new CreateWindow();
	private RemoveWindow mRemoveWindow = new RemoveWindow();
	private Handler mHandler = new Handler();
	private WindowManager mWindowManager;
	private TextView mDialogText;
	protected EditText mSearchText;
	protected String mFilter;

	private void createWindow() {
		mReady = true;
        WindowManager.LayoutParams lp = new WindowManager.LayoutParams(
                LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,
                WindowManager.LayoutParams.TYPE_APPLICATION,
                WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE
                        | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
                PixelFormat.TRANSLUCENT);
        mWindowManager.addView(mDialogText, lp);
	}
	
	private void removeWindow() {
		if (mShowing) {
			mShowing = false;
			mDialogText.setVisibility(View.INVISIBLE);
		}
	}
   
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        NTLog.d(TAG, StackTraceUtil.getMethodName()
                + " savedInstanceState=" + (null == savedInstanceState ? "null" : savedInstanceState.toString()));
        /**
         * 一定要设置为true,才会调用onCreateOptionsMenu
         */
        setHasOptionsMenu(true);
        mRootView = inflater.inflate(R.layout.fragment_tip_base, container, false);
        mTabDiscussTip = (TabDiscussTip)mRootView.findViewById(R.id.discusstip_tab);
        mTabDiscussTip.setVisibility(View.GONE);
        mTabDiscussTip.setOnTabSelectListener(new OnTabSelectListener() {

            @Override
            public void onTabSelected(View tabView, int index) {
                onTabChange(index);
                onResetData();
            }

            @Override
            public void onTabReSelected(View tabView, int index) {
                
            }
            
        });
        
        mSearchText = (EditText)mRootView.findViewById(R.id.search);
        mSearchText.setVisibility(View.VISIBLE);
        mSearchText.addTextChangedListener(new TextWatcher() {

            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
                
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                
            }

            @Override
            public void afterTextChanged(Editable s) {
                do {
                    String newText = s.toString().trim();
                    String newFilter = !TextUtils.isEmpty(newText) ? newText : null;
                    if (mFilter == null && newFilter == null) {
                        break;
                    }
                    if (mFilter != null && mFilter.equals(newFilter)) {
                        break;
                    }
                    mFilter = newFilter;
                    
                    loadCursor();
                } while (false);
            }
            
        });
        
        int resid = 0;
        if (mType == ItemViewTipBase.TYPE_USER) {
        	resid = R.string.tip_user;
        } else if (mType == ItemViewTipBase.TYPE_SOURCE) {
        	resid = R.string.tip_source;
        } else if (mType == ItemViewTipBase.TYPE_SUBJECT) {
        	resid = R.string.tip_subject;
        } else if (mType == ItemViewTipBase.TYPE_TOPIC) {
        	resid = R.string.tip_topic;
        }
        mSearchText.setHint(resid);
        
        mAlphaIndex = new AlphabetIndexer(null, 4, CHARACTERS);
        mLetterIndexView = (LetterIndexView)mRootView.findViewById(R.id.letterIndexView);
        mLetterIndexView.setVisibility(View.GONE);
        mLetterIndexView.setOnLetterChangeListener(this);
        
        // 初始化listview
        mListView = (LoadingListView)mRootView.findViewById(R.id.tip_listview);
        mAdapter = getAdapter();
        mListView.setAdapter(mAdapter);
        loadCursor();
        mListView.setOnItemClickListener(this);
        
        mWindowManager = (WindowManager)getActivity().getSystemService(Context.WINDOW_SERVICE);
        mDialogText = (TextView) inflater.inflate(R.layout.list_position, null);
        mDialogText.setVisibility(View.INVISIBLE);
        mHandler.post(mCreateWindow);
        return mRootView;
    }
    
    protected void onResetData() {
        mListView.setAdapter(null);
        mAdapter = getAdapter();
        mListView.setAdapter(mAdapter);
        loadCursor();
        
    }
    
    protected void onTabChange(int index) {
        NTLog.d(TAG, StackTraceUtil.getMethodName());
    }
    
    protected CursorAdapter getAdapter() {
        NTLog.d(TAG, StackTraceUtil.getMethodName());
        return null;
    }
    
    protected void loadCursor() {
        NTLog.d(TAG, StackTraceUtil.getMethodName());
        if (bFirst) {
            bFirst = false;
            getSherlockActivity().getSupportLoaderManager().initLoader(mLoadId, null, this).forceLoad();
        } else {
            getSherlockActivity().getSupportLoaderManager().restartLoader(mLoadId, null, this);
        }
    }
    
    @Override
    public void onResume() {
        NTLog.d(TAG, StackTraceUtil.getMethodName());
    	super.onResume();
    	mReady = true;
    }
    
    @Override
    public void onPause() {
        NTLog.d(TAG, StackTraceUtil.getMethodName());
        super.onPause();
        removeWindow();
        mReady = false;
    }
    
    @Override
    protected void onLeftTopBack() {
        getSherlockActivity().finish();
    }
    
    @Override
    public void onDestroy() {
        NTLog.d(TAG, StackTraceUtil.getMethodName());
        super.onDestroy();
        /**
         * 一定要销毁Loader,不然就出现不执行onCreateLoader而执行onLoadFinished问题
         */
        getSherlockActivity().getSupportLoaderManager().destroyLoader(mLoadId);
        if (mAdapter instanceof AdapterTip) {
            ((AdapterTip)mAdapter).setAlphabetIndexer(null);
        }
        mAdapter = null;
        mTabDiscussTip = null;
        mListView = null;
        mRootView = null;
        if (null != mWindowManager) {
        	mWindowManager.removeView(mDialogText);
        }
        mWindowManager = null;
        mDialogText = null;
        mReady = false;
        mAlphaIndex = null;
        mSearchText = null;
    }

    protected String getItemInfo(Object obj, int position) {
        NTLog.d(TAG, StackTraceUtil.getMethodName());
        return null;
    }
    
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        NTLog.d(TAG, StackTraceUtil.getMethodName() + " position=" + position);
        getSherlockActivity().getSupportFragmentManager().popBackStack();
        Object obj = parent.getAdapter().getItem(position);
        if (null == obj) {
            return;
        }
        
        String data = getItemInfo(obj, position);
        sendData(data);
        onLeftTopBack();
    }
    
    protected void sendData(String value) {
    	if (TextUtils.isEmpty(value)) {
            return;
        }
        LoopBack loopBack = new LoopBack();
        loopBack.mType = mType;
        loopBack.mData = value;
        
        XoneService.getInstance().doLoopBack(loopBack);
    }
    
    /**
     * Loader相关函数 该函数不能返回null,不然下次执行该函数后onLoadFinished就不会被执行
     */
    @Override
    public Loader<Cursor> onCreateLoader(int id, Bundle args) {
        NTLog.d(TAG, StackTraceUtil.getMethodName());
        StringBuffer buffer = new StringBuffer();
        String sort = null;
        switch (mType) {
            case ItemViewTipBase.TYPE_USER:
                if (TextUtils.isEmpty(mFilter)) {
                    buffer.append(DiscussTipTable.C_TYPE).append(" = ").append(ManagerDiscussTip.TYPE_USER)
                    .append(" AND ( ").append(DiscussTipTable.C_SUBTYPE).append(" = ").append(ManagerDiscussTip.SUBTYPE_2)
                    .append(" OR ").append(DiscussTipTable.C_SUBTYPE).append(" = ").append(ManagerDiscussTip.SUBTYPE_3)
                    .append(" )");
                    
                } else {
                    buffer.append(DiscussTipTable.C_TYPE).append(" = ").append(ManagerDiscussTip.TYPE_USER)
                    .append(" AND ( ").append(DiscussTipTable.C_SUBTYPE).append(" = ").append(ManagerDiscussTip.SUBTYPE_2)
                    .append(" OR ").append(DiscussTipTable.C_SUBTYPE).append(" = ").append(ManagerDiscussTip.SUBTYPE_3)
                    .append(" ) AND ").append(DiscussTipTable.C_CONTENT).append(" like ").append(DatabaseUtils.sqlEscapeString('%' + mFilter + '%'));
                }
                sort = DiscussTipTable.C_PINYIN + " ASC, " + DiscussTipTable.C_CONTENT + " DESC";
                break;
            case ItemViewTipBase.TYPE_SOURCE:
                if (TextUtils.isEmpty(mFilter)) {
                    buffer.append(DiscussTipTable.C_TYPE).append(" = ").append(ManagerDiscussTip.TYPE_SUBSCRIBE)
                    .append(" AND ( ").append(DiscussTipTable.C_SUBTYPE).append(" = ").append(ManagerDiscussTip.SUBTYPE_2)
                    .append(" OR ").append(DiscussTipTable.C_SUBTYPE).append(" = ").append(ManagerDiscussTip.SUBTYPE_3)
                    .append(" )");
                } else {
                    buffer.append(DiscussTipTable.C_TYPE).append(" = ").append(ManagerDiscussTip.TYPE_SUBSCRIBE)
                    .append(" AND ( ").append(DiscussTipTable.C_SUBTYPE).append(" = ").append(ManagerDiscussTip.SUBTYPE_2)
                    .append(" OR ").append(DiscussTipTable.C_SUBTYPE).append(" = ").append(ManagerDiscussTip.SUBTYPE_3)
                    .append(" ) AND ").append(DiscussTipTable.C_CONTENT).append(" like ").append(DatabaseUtils.sqlEscapeString('%' + mFilter + '%'));
                }
                sort = DiscussTipTable.C_PINYIN + " ASC, " + DiscussTipTable.C_CONTENT + " DESC";
                break;
            case ItemViewTipBase.TYPE_TOPIC:
                if (TextUtils.isEmpty(mFilter)) {
                    buffer.append(DiscussTipTable.C_TYPE).append(" = ").append(ManagerDiscussTip.TYPE_TOPIC);
                } else {
                    buffer.append(DiscussTipTable.C_TYPE).append(" = ").append(ManagerDiscussTip.TYPE_TOPIC)
                    .append(" AND ").append(DiscussTipTable.C_CONTENT).append(" like ").append(DatabaseUtils.sqlEscapeString('%' + mFilter + '%'));
                }
                sort = DiscussTipTable.C_PINYIN + " ASC, " + DiscussTipTable.C_CONTENT + " DESC";
                break;
            case ItemViewTipBase.TYPE_SUBJECT:
                if (TextUtils.isEmpty(mFilter)) {
                    buffer.append(DiscussTipTable.C_TYPE).append(" = ").append(ManagerDiscussTip.TYPE_SUBJECT)
                    .append(" AND ( ").append(DiscussTipTable.C_SUBTYPE).append(" = ").append(ManagerDiscussTip.SUBTYPE_2)
                    .append(" OR ").append(DiscussTipTable.C_SUBTYPE).append(" = ").append(ManagerDiscussTip.SUBTYPE_3)
                    .append(" )");
                } else {
                    buffer.append(DiscussTipTable.C_TYPE).append(" = ").append(ManagerDiscussTip.TYPE_SUBJECT)
                    .append(" AND ").append(DiscussTipTable.C_CONTENT).append(" like ").append(DatabaseUtils.sqlEscapeString('%' + mFilter + '%'));
                }
                sort = DiscussTipTable.C_PINYIN + " ASC, " + DiscussTipTable.C_CONTENT + " DESC";
                break;
        }
        
        return new CursorLoader(
                getActivity(), 
                DiscussTipTable.CONTENT_URI, 
                ManagerDiscussTip.Projection, 
                buffer.toString(), 
                null, 
                sort);
    }

    @Override
    public void onLoadFinished(Loader<Cursor> loader, Cursor cursor) {
        NTLog.d(TAG, StackTraceUtil.getMethodName() + " cursor.getCount()=" + cursor.getCount());
        if (null != mAdapter && null != cursor) {
            mAdapter.swapCursor(cursor);
        }
        
        if (null != mAlphaIndex && null != cursor && View.VISIBLE == mLetterIndexView.getVisibility()) {
        	mAlphaIndex.setCursor(cursor);
        }
        
        // TODO 如果cursor内容为空要进行不同提示
        
    }

    @Override
    public void onLoaderReset(Loader<Cursor> loader) {
        NTLog.d(TAG, StackTraceUtil.getMethodName());
        if (null != mAdapter) {
            mAdapter.swapCursor(null);
        }
    }

	@Override
	public void onLetterChange(int index) {
	    NTLog.d(TAG, StackTraceUtil.getMethodName() + " index=" + index);
	    /**
	     * 显示提示字母
	     */
		if (mReady) {
            char firstLetter = LetterIndexView.CHARACTER_ARRAY[index].charAt(0);
            if (!mShowing) {
                mShowing = true;
                mDialogText.setVisibility(View.VISIBLE);
            }
            mDialogText.setText(((Character)firstLetter).toString());
            mHandler.removeCallbacks(mRemoveWindow);
            mHandler.postDelayed(mRemoveWindow, 1500);
        }
		
		/**
		 * 对listview进行定位
		 */
		if (null == mAlphaIndex) {
            return;
        }
		try {
		    int position = mAlphaIndex.getPositionForSection(index);
	        if (position >= mAdapter.getCount()) {
	            return;
	        }
	        
	        if (index == mAlphaIndex.getSectionForPosition(position)) {
	            mListView.getRefreshableView().setSelection(position);
	        }
        } catch (Exception e) {
            e.printStackTrace();
        }
	}
}
